import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Table, Row, Col} from 'antd';
import {PAGE, TABLE, DATE_FORMAT, DATETIME_FORMAT, PAGINATION_OPTIONS} from '../constants';
import {formatAmount, formatDateTime, conventSorter, conventEnumValueToString} from '../utils';
import {getUrl} from './utils';
import {getDetail} from './api';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {currency} from '../Enum';
import routes from './routes';

export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
        id: '',
        dealerId: '',
        month: undefined,
        year: undefined,
        details: [],
        isDesc: false,
        sortField: 'partCode',
        currentCondition: {},
    };
    componentDidMount() {
        if(this.props.id) {
            const order = getUrl(this.props.history.location.search);
            this.setState({
                dealerId: order.dealerId,
                month: order.month,
                year: order.year,
            });
            this.onQuery({
                dealerId: order.dealerId,
                month: order.month,
                year: order.year,
                sortField: this.state.sortField,
                pageSize: PAGE.size
            });
        } else {
            const condition = {
                dealerId: this.state.dealerId,
                month: this.state.month,
                year: this.state.year,
                sortField: this.state.sortField,
                pageIndex: PAGE.index,
                pageSize: this.state.pageSize,
                isDesc: this.state.isDesc
            };
            this.onQuery(condition);
        }
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = this.state.currentCondition;

        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    };
    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    };
    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    };
    onQuery = condition => {
        this.setState({loading: true});
        const newCondition = {
            dealerId: this.state.dealerId,
            month: this.state.month,
            year: this.state.year,
            ...condition
        };
        getDetail(newCondition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        message: '',
                        details: res.data.content,
                        currentCondition: Object.assign({}, condition, {
                            pageSize: res.data.pageSize,
                            pageIndex: res.data.pageIndex,
                            totalPages: res.data.totalPages,
                            totalElements: res.data.totalElements,
                        }),
                    });
                else
                    this.setState({
                        loading: true,
                        data: [],
                        message: res.message
                    });
            });
    }
    render() {
        const {details} = this.state;
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, totalElements} = this.state.currentCondition;
        const columns = [{
            title: formatMessage({
                id: 'detailPanel.column.partCode',
                defaultMessage: '备件编号（奇瑞）'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partName',
                defaultMessage: '备件名称（奇瑞）'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partCodeLocal',
                defaultMessage: '备件编号（本地）'
            }),
            dataIndex: 'partCodeLocal',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partNameLocal',
                defaultMessage: '备件名称（本地）'
            }),
            dataIndex: 'partNameLocal',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partInQuantity',
                defaultMessage: '月入库数'
            }),
            dataIndex: 'partInQuantity',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partOutQuantity',
                defaultMessage: '月出库数'
            }),
            dataIndex: 'partOutQuantity',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.stockQuantity',
                defaultMessage: '库存数量'
            }),
            dataIndex: 'stockQuantity',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.purchaseCurrency',
                defaultMessage: '采购币种'
            }),
            dataIndex: 'purchaseCurrency',
            // render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.purchasePrice',
                defaultMessage: '采购价'
            }),
            dataIndex: 'purchasePrice',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.saleCurrency',
                defaultMessage: '销售币种'
            }),
            dataIndex: 'saleCurrency',
            // render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.salePrice',
                defaultMessage: '销售价'
            }),
            dataIndex: 'salePrice',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.updateTime',
                defaultMessage: '上传时间'
            }),
            dataIndex: 'updateTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.invoicedDate',
                defaultMessage: '最近一次采购日期'
            }),
            dataIndex: 'invoicedDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.sluggishQuantity',
                defaultMessage: '呆滞数量'
            }),
            dataIndex: 'sluggishQuantity',
        }];
        const pagination = {
            total: totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        return (
            <div className="detail">
                <Card>
                    <DescriptionList size="large" title={<Row><Col span={6}>{
                        formatMessage({
                            id: 'detailPanel.card.partInvoiceTrack',
                            defaultMessage: '备件进销存报表清单'
                        })
                    }</Col></Row>}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            loading={this.props.loading || this.state.loading}
                            onChange={this.handleTableChange}
                            pagination={pagination}
                            dataSource={details}
                            {...TABLE} />
                    </DescriptionList>
                </Card>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.props.loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'detailPanel.btn.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,

};

import {connect} from 'react-redux';
import {injectIntl} from './intl';
import {tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);
const mapStateToProps = (state, props) => ({
    id: props.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    permissions: getPermissions(state),
    detail: getDetailData(state),
    isDealerUser: state.getIn(['page', 'domainData', 'init', 'isDealerUser']),
});
const mapDispatchToProps = (dispatch, props) => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    init: () => dispatch(getDetail(props.id)),
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
